package com.esun.payment_api.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.esun.common.api.CommonResult;
import com.esun.common.bean.PageRequest;
import com.esun.common.constant.Constants;
import com.esun.common.utils.*;
import com.esun.payment_api.bean.AttachOpenIdBean;
import com.esun.payment_api.bean.WxExaminerBean;
import com.esun.payment_api.bean.WxMessageBean;
import com.esun.payment_api.dao.AccessToken;
import com.esun.payment_api.domain.*;
import com.esun.payment_api.mapper.UserMapper;
import com.esun.payment_api.mapper.XcxInfoMapper;
import com.esun.payment_api.service.LogService;
import com.esun.payment_api.service.UserService;
import com.esun.payment_api.service.XcxInfoService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;

@Service
public class XcxInfoServiceImpl implements XcxInfoService {

    private static AccessToken at;

    @Resource
    private XcxInfoMapper xcxInfoMapper;

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserService userService;

    @Resource
    private LogService logService;

    public static String getToken(){
        //若token不存在 or 已过期，则重新请求一次
        if (at == null || at.isExpired()){
            getAccessToken();
        }
        return at.getAccessToken();
    }

    /**
     * 获取access_token
     */
    private static void getAccessToken() {
        String tokenUrl = Constants.ACCESS_TOKEN_URL;
        String appId = Constants.APP_ID;
        String appSecret = Constants.APP_SECRET;
        tokenUrl = tokenUrl.replace("APPID", appId)
                .replace("APPSECRET", appSecret);
        String getToken = null;
        try {
            //请求微信服务器调用获取 access_token 的接口
            getToken = HttpUtil.get(tokenUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }

        JSONObject jsonObject = JSON.parseObject(getToken);
        String accessToken = (String) jsonObject.get("access_token");
        Integer expiresIn = (Integer) jsonObject.get("expires_in");
        //创建token对象，并存储
        at = new AccessToken(accessToken, String.valueOf(expiresIn));
        System.out.println("系统当前时间：" + System.currentTimeMillis());
        System.out.println("获取AccessToken：" + getToken);
    }

    @Override
    public XcxInfo getApp() {
        return xcxInfoMapper.getApp();
    }

    @Override
    public int updateById(XcxInfo xcxInfo) {
        return xcxInfoMapper.updateByPrimaryKeySelective(xcxInfo);
    }

    @Override
    public String sendWxMessage(Integer flowId) {
        /**
         * 1、通过flowId 获取当前审批节点
         * 2、获取发票或者到款的某些信息
         * 3、拼接字符串param
         * 4、推送消息给用户
         */
        String result = null;
        WxMessageBean wxMessage = getWxMessageBean(flowId);
        List<WxExaminerBean> wxExaminerBeanList = getOpenIdList(flowId);    //获取下一级审批人openId
        List<WxExaminerBean> operatorList = getOperatorOpenIdList(flowId);  //获取发起人openId（如果审批通过）

        if (operatorList.size()>0) {
            wxExaminerBeanList.addAll(operatorList);
        }

        try {
            String accessToken = getToken();
            String url = Constants.SEND_URL.replace("ACCESS_TOKEN", accessToken);

            for (WxExaminerBean wx : wxExaminerBeanList) {
                try {
                    if (wx == null || BlankUtils.isBlank(wx.getOpenId())){
                        continue;
                    }
                    //没有关联小程序，没有跳转页面
                   /* String param = "{\"touser\":\"" + wx.getOpenId() +              //openId
                            "\"," +
                            "\"template_id\":\"" + Constants.TEMPLATE_ID +          //template_id
                            "\",\"url\":\"" + "" +     //跳转的连接
                            "\",\"topcolor\":\"#FF0000\"," +
                            "\"data\":{" +
                            "\"first\":{" +
                            "\"value\":\"" + wxMessage.getName() +                  //值1
                            "\",\"color\":\"#173177\"}," +
                            "\"keyword1\":{" +
                            "\"value\":\"" + wxMessage.getDeptName() +              //值2
                            "\",\"color\":\"#173177\"}," +
                            "\"keyword2\":{\"value\":\"" + wxMessage.getCode() +    //值3
                            "\",\"color\":\"#173177\"}," +
                            "\"keyword3\":{\"value\":\"" + "￥" + wxMessage.getMoney() + //值4
                            "\",\"color\":\"#173177\"}," +
                            "\"keyword4\":{\"value\":\"" + wxMessage.getApplyTime() +   //值5
                            "\",\"color\":\"#173177\"}," +
                            "\"remark\":{\"value\":\"" + wxMessage.getRemarks() +       //值6
                            "\",\"color\":\"#173177\"}}}";*/

                    /**
                     * 关联小程序，跳转，但是 HttpUtil.post(url, param) 请求会报错：
                     * {"errcode":40013,"errmsg":"invalid appid rid: 6317ffc0-6ad136bd-52764865"}
                     * 解决：公众号与小程序都绑定在同一个开放平台，公众号关联小程序
                     */
                    String param = "{\"touser\":\"" + wx.getOpenId() +              //openId
                            "\"," +
                            "\"template_id\":\"" + Constants.TEMPLATE_ID +          //template_id
                            "\",\"url\":\"" + "" +     //跳转的连接
                            "\",\"miniprogram\":{" +
                            "\"appid\":\"" + Constants.XCX_APP_ID +                 //小程序的appId
                            "\",\"pagepath\":\"" +      //开发文档里是pagepath，应该写成page/index/index，注意前面不能有/，如果有参数也可以加在后面，比如page/index/index?type=1&age=16。
                            "pages/loading/loading?openid=" + wx.getOpenId() + "&isGzh=1" +    //小程序的路径
                            "\"}," +
                            "\"topcolor\":\"#FF0000\"," +
                            "\"data\":{" +
                            "\"first\":{" +
                            "\"value\":\"" + wxMessage.getName() +                  //值1
                            "\",\"color\":\"#173177\"}," +
                            "\"keyword1\":{" +
                            "\"value\":\"" + wxMessage.getDeptName() +              //值2
                            "\",\"color\":\"#173177\"}," +
                            "\"keyword2\":{\"value\":\"" + wxMessage.getCode() +    //值3
                            "\",\"color\":\"#173177\"}," +
                            "\"keyword3\":{\"value\":\"" + "￥" + wxMessage.getMoney() + //值4
                            "\",\"color\":\"#173177\"}," +
                            "\"keyword4\":{\"value\":\"" + (BlankUtils.isBlank(wxMessage.getApplyTime()) ? "" : wxMessage.getApplyTime()) +   //值5
                            "\",\"color\":\"#173177\"}," +
                            "\"remark\":{\"value\":\"" + (BlankUtils.isBlank(wxMessage.getRemarks()) ? "" : wxMessage.getRemarks()) +       //值6
                            "\",\"color\":\"#173177\"}}}";

                    String post = HttpUtil.post(url, param);
                    System.out.println("post body param：" + post);
                } catch (Exception e1) {
                    e1.printStackTrace();
                }
            }

            result = "推送成功!";
        } catch (Exception e) {
            result = "推送失败!";
            e.printStackTrace();
            logService.writeErrorLog(e.getMessage(),"消息推送");
        }
        return result;
    }

    @Override
    public WxMessageBean getWxMessageBean(Integer flowId) {
        return xcxInfoMapper.getWxMessage(flowId);
    }

    @Override
    public List<WxExaminerBean> getOpenIdList(Integer flowId) {
        return xcxInfoMapper.getOpenIdList(flowId);
    }

    @Override
    public List<WxExaminerBean> getOperatorOpenIdList(Integer flowId) {
        return xcxInfoMapper.getOperatorOpenIdList(flowId);
    }

    @Override
    public CommonResult attachOpenId(AttachOpenIdBean attachOpenIdBean){
        logService.writeCustomLog("测试绑定","服务层接收attachOpenId","测试");
        try {
            HashMap<String, String> map = new HashMap<>();
            map.put("loginName", attachOpenIdBean.getUsername());

            PageRequest pageRequest = new PageRequest();
            pageRequest.setConditions(map);
            User user = userMapper.getUserByUsername(pageRequest);
            System.out.println("绑定时传来的加密后的密码："+attachOpenIdBean.getPassword());
            System.out.println("正确的密码加密之后："+AESUtils.encrypt("12"));
            if (user!=null) {
                //解密密码，在前端加密后启用
                attachOpenIdBean.setPassword(AESUtils.decrypt(attachOpenIdBean.getPassword()));
                if(SecurityUtils.matchesPassword(attachOpenIdBean.getPassword(), user.getPassword())) {
                    if(user.getStatus().equals("2")){
                        return CommonResult.failed("绑定失败，该账号已失效");
                    }
//                    更新用户的openId
                    user.setWxOpenId(attachOpenIdBean.getOpenId());
                    user.setWxUnionId(attachOpenIdBean.getUnionId());

                    userService.editUserBasic(user);

                    return CommonResult.success("绑定成功");
                } else {
                    return CommonResult.failed("绑定失败，密码错误");
                }
            } else {
                return CommonResult.failed("绑定失败，该用户不存在");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return CommonResult.failed("绑定失败，参考原因："+e.getMessage());
        }
    }

    @Override
    public Integer getFlowIdAndSend(Short flowType, Integer fromId){
        try{
            EsunFlow esunFlow = xcxInfoMapper.getOngoingFlow(flowType,fromId);
            sendWxMessage(esunFlow.getId());
            return esunFlow.getId();
        }catch (Exception e){
            e.printStackTrace();
        }
        return 0;
    }

    public CommonResult test(Integer flowId){
        List<WxExaminerBean> list = getOperatorOpenIdList(flowId);
        return CommonResult.success(list);
    }

}
